package com.produce.user.service;


import com.common.dao.base.constant.SystemStaticConst;
import com.common.dao.base.dao.BaseDao;
import com.common.dao.base.service.BaseService;
import com.common.dao.util.RedisCache;
import com.linzf.common.util.DateUtil;
import com.linzf.common.util.JsonUtils;
import com.linzf.common.util.Md5Util;
import com.linzf.common.util.TokenUtil;
import com.produce.user.dao.RoleTreeDao;
import com.produce.user.dao.UserAssociateRoleDao;
import com.produce.user.dao.UserDao;
import com.produce.user.entity.RoleTree;
import com.produce.user.entity.User;
import com.produce.user.entity.UserAssociateRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类描述：用户操作的service
 * @author linzf
 */
@Service
@Transactional(rollbackFor={IllegalArgumentException.class})
public class UserService extends BaseService<User> {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleTreeDao roleTreeDao;

    @Autowired
    private UserAssociateRoleDao userAssociateRoleDao;

    @Autowired
    private RedisCache redisCache;
    /** 加密的盐值 */
    @Value("${base.salt}")
    public String salt;
    /** 基础密码 */
    @Value("${base.password}")
    public String basePassword;

    @Override
    protected BaseDao<User> getDao() {
        return this.userDao;
    }

    /**
     * 功能描述：获取用户数据
     * @param entity
     * @return
     */
    public Map<String,Object> getUser(Map<String,Object> entity) {
        User user = super.get(JsonUtils.map2object(entity,User.class));
        Map<String,Object> map = JsonUtils.objToMap(user);
        UserAssociateRole uar = new UserAssociateRole();
        uar.setUserId(user.getUserId());
        List<UserAssociateRole> userAssociateRoles = userAssociateRoleDao.select(uar);
        List<String> userRoles = new ArrayList<>();
        for(UserAssociateRole u:userAssociateRoles){
            userRoles.add(u.getRoleId());
        }
        map.put("userRoles",userRoles);
        return map;
    }

    @Override
    public boolean delete(User entity) throws Exception {
        UserAssociateRole userAssociateRole = new UserAssociateRole();
        userAssociateRole.setUserId(entity.getUserId());
        userAssociateRoleDao.delete(userAssociateRole);
        return super.delete(entity);
    }

    /**
     * 功能描述：实现更新用户
     * @param entity
     * @return
     * @throws Exception
     */
    public boolean updateUser(Map<String,Object> entity) throws Exception {
        List<String> userRoles = (List)entity.get("userRoles");
        User user = JsonUtils.map2object(entity,User.class);
        UserAssociateRole userAssociateRole = new UserAssociateRole();
        userAssociateRole.setUserId(user.getUserId());
        userAssociateRoleDao.delete(userAssociateRole);
        UserAssociateRole uar = null;
        for (String roleId : userRoles) {
            uar = new UserAssociateRole();
            uar.setUserId(user.getUserId());
            uar.setRoleId(roleId);
            userAssociateRoleDao.insert(uar);
        }
        return userDao.updateUser(user)>0;
    }

    /**
     * 功能描述：新增用户的时候保存用户数据
     * @param entity
     * @return
     * @throws Exception
     */
    public boolean saveUser(Map<String,Object> entity) throws Exception {
        List<String> userRoles = (List)entity.get("userRoles");
        User user = JsonUtils.map2object(entity,User.class);
        user.setPassword(Md5Util.getMd5(basePassword,salt));
        user.setCrtDate(DateUtil.currentMillitm());
        // 获取当前登录的用户的信息
        Map<String,Object> obj = this.getUser(redisCache);
        User loginUser = JsonUtils.map2object(obj,User.class);
        user.setCrtUser(loginUser.getUserName());
        user.setCrtUserId(loginUser.getUserId());
        boolean success = super.save(user);
        UserAssociateRole userAssociateRole;
        for (String roleId : userRoles) {
            userAssociateRole = new UserAssociateRole();
            userAssociateRole.setUserId(user.getUserId());
            userAssociateRole.setRoleId(roleId);
            userAssociateRoleDao.insert(userAssociateRole);
        }
        return success;
    }

    @Override
    public boolean save(User entity) throws Exception {
        entity.setPassword(Md5Util.getMd5(basePassword,salt));
        entity.setCrtDate(DateUtil.currentMillitm());
        // 获取当前登录的用户的信息
        Map<String,Object> obj = this.getUser(redisCache);
        User user = JsonUtils.map2object(obj,User.class);
        entity.setCrtUser(user.getUserName());
        entity.setCrtUserId(user.getUserId());
        return super.save(entity);
    }

    /**
     * 功能描述：根据用户的登录的token来判断用户是否有访问权限
     * @param auth
     * @return
     */
    public Map<String,Object> authByToken(Map<String,Object> auth){
        Map<String,Object> result = new HashMap<>(2);
        User user = JsonUtils.map2object(auth,User.class);
        user = redisCache.getObject(user.getToken(),User.class);
        if(user!=null){
            redisCache.setObject(user.getToken(),user,3600);
            result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
        }else{
            result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
        }
        return result;
    }

    /**
     * 功能描述： 根据用户的token来获取当前用户登录的信息
     * @param user
     * @return
     */
    public  Map<String,Object>  getUserByToken(User user){
        Map<String,Object> result = new HashMap<>(2);
        Map<String,Object> userInfo = redisCache.getObject(user.getToken(),Map.class);
        user = JsonUtils.map2object(userInfo,User.class);
        if(user!=null){
            result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
            result.put("user",user);
        }else{
            result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
        }
        return result;
    }

    /**
     * 功能描述：根据账号和密码实现用户的登录功能
     * @param entity
     * @return
     */
    public Map<String,Object> userLogin(User entity){
        Map<String,Object> result = new HashMap<>(2);
        entity.setPassword(Md5Util.getMd5(entity.getPassword(),salt));
        entity = userDao.userLogin(entity);
        if(entity!=null){
            String token  =  TokenUtil.getUserToken();
            // 用来刷新的token
            String refreshToken = TokenUtil.getUserToken();
            result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
            result.put("token",token);
            entity.setToken(result.get("token").toString());
            // 更新用户登录的token和登录时间
            userDao.updateToken(entity);
            // 将当前的用户数据转化为map键值对
            Map<String,Object> userInfo = JsonUtils.objToMap(entity);
            // 获取当前登录用户的所有的角色数据
            List<RoleTree> roleTreeList = roleTreeDao.queryUserTree(entity);
            StringBuilder s = new StringBuilder();
            for(RoleTree r:roleTreeList){
                 s.append(r.getUrl()+":");
            }
            // 重新刷新token的信息
            userInfo.put("treeInfo",s.toString());
            redisCache.setObject(token,userInfo,3600);
            redisCache.setString(token+"refresh",refreshToken,7200);
            redisCache.setObject(refreshToken,userInfo,7200);
        }else{
            result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
            result.put("token", "");
        }
        return result;
    }


}
